package com.agou.ssh.core.db;

import java.io.File;
import java.net.URL;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {
	private static SessionFactory sessionFactory = null;
	static {
		URL url = HibernateUtil.class.getResource("/");
		String strXml = url.getFile() + "hibernate.maping.xml";
		File xmlFile = new File(strXml);
		Configuration cfg = new Configuration();  
		SAXReader saxReader = new SAXReader();
		Document document = null;
		try {
			document = saxReader.read(xmlFile);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		Element rootEle = document.getRootElement();// 取得根元素
		String basePath = rootEle.elementText("base-path");
		@SuppressWarnings("unchecked")
		List<Element> mapList = rootEle.element("mappings").elements();
		Element mapEle;
		for (int i = 0; i < mapList.size(); i++) {
			mapEle = mapList.get(i);
			cfg.addFile(basePath + mapEle.getText());
		}
		cfg.configure();
		ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
		sessionFactory = cfg.buildSessionFactory(sr);
	}
	
	
	/**
	 * 测试过程中使用数据库连接
	 * 当前方法不建议在开发中使用
	 * @return
	 */
	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	
}
